// 渲染请求参数表格
function renderParamsTable(params) {
    if (!params || !params.length) {
        return '<tr><td colspan="4" class="text-center">无参数</td></tr>';
    }

    return params.map(param => `
        <tr>
            <td>${param.name}</td>
            <td>${param.type}</td>
            <td>${param.required ? '<span class="text-danger">是</span>' : '否'}</td>
            <td>${param.description}</td>
        </tr>
    `).join('');
}

// 渲染响应参数表格
function renderResponseParamsTable(params, level = 0) {
    if (!params || !params.length) {
        return '<tr><td colspan="3" class="text-center">无参数</td></tr>';
    }

    return params.map(param => {
        let prefix = level > 0 ? '└─'.padStart(level * 2 + 2, '　') : '';
        let html = `
            <tr>
                <td>${prefix}${param.name}</td>
                <td>${param.type}</td>
                <td>${param.description}</td>
            </tr>
        `;

        if (param.children && param.children.length) {
            html += renderResponseParamsTable(param.children, level + 1);
        }

        return html;
    }).join('');
}

// 渲染调试表单
function renderDebugForm(config) {
    if (!config || !config.fields) return '';

    return `
        <div class="row g-3">
            ${config.fields.map(field => renderFormField(field)).join('')}
        </div>
    `;
}

// 渲染表单字段
function renderFormField(field) {
    const colClass = field.col ? `col-md-${field.col}` : 'col-12';
    let input = '';

    switch (field.type) {
        case 'text':
            input = `
                <input type="text" 
                       class="form-control" 
                       name="${field.name}" 
                       placeholder="${field.placeholder || ''}"
                       value="${field.value || ''}"
                       ${field.required ? 'required' : ''}>
            `;
            break;
        case 'file':
            input = `
                <input type="file" 
                       class="form-control" 
                       name="${field.name}" 
                       placeholder="${field.placeholder || ''}"
                       ${field.required ? 'required' : ''}>
            `;
            break;
        case 'number':
            input = `
                <input type="${field.type}" 
                       class="form-control" 
                       name="${field.name}" 
                       placeholder="${field.placeholder || ''}"
                       value="${field.value || ''}"
                       ${field.required ? 'required' : ''}>
            `;
            break;

        case 'password':
            input = `
                <input type="password" 
                       class="form-control" 
                       name="${field.name}" 
                       placeholder="${field.placeholder || ''}"
                       value="${field.value || ''}"
                       ${field.required ? 'required' : ''}>
            `;
            break;

        case 'select':
            input = `
                <select class="form-select" 
                        name="${field.name}"
                        ${field.required ? 'required' : ''}>
                    ${field.options.map(opt => `
                        <option value="${opt.value}" 
                                ${field.value === opt.value ? 'selected' : ''}>
                            ${opt.label}
                        </option>
                    `).join('')}
                </select>
            `;
            break;

        case 'textarea':
            input = `
                <textarea class="form-control" 
                         name="${field.name}"
                         placeholder="${field.placeholder || ''}"
                         rows="${field.rows || 3}"
                         ${field.required ? 'required' : ''}
                         >${field.value || ''}</textarea>
            `;
            break;
        case 'datetime-local':
            input = `
                <input type="datetime-local" 
                       class="form-control" 
                       name="${field.name}" 
                       placeholder="${field.placeholder || ''}"
                       value="${field.value || ''}"
                       ${field.required ? 'required' : ''}>
            `;
            break;
    }

    return `
        <div class="${colClass}">
            ${input}
        </div>
    `;
}

// 复制文本到剪贴板
function copyToClipboard(text) {
    // 创建临时文本区域
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';
    document.body.appendChild(textarea);

    try {
        // 选择文本
        textarea.select();
        textarea.setSelectionRange(0, 99999);
        // 行复制
        const successful = document.execCommand('copy');

        if (successful) {
            showCopyTip(true);
        } else {
            showCopyTip(false);
        }
    } catch (err) {
        console.error('复制失败:', err);
        showCopyTip(false);
    } finally {
        // 移除临时元素
        document.body.removeChild(textarea);
    }
}

// 显示复制提示
function showCopyTip(success) {
    const tip = document.createElement('div');
    tip.className = `copy-tip ${success ? 'success' : 'error'}`;
    tip.innerHTML = `
        <i class="fa fa-${success ? 'check' : 'times'}"></i>
        ${success ? '复制成功' : '复制失败'}
    `;
    document.body.appendChild(tip);

    // 添加动画类
    setTimeout(() => tip.classList.add('show'), 10);

    // 自动移除提示
    setTimeout(() => {
        tip.classList.remove('show');
        setTimeout(() => document.body.removeChild(tip), 300);
    }, 2000);
}

// 处理表单数据，将带索引的字段转换为数组
function processFormData(formData) {
    const result = {};
    const arrayFields = new Map(); // 用于存储数组字段

    // 遍历所有表单字段
    for (let [key, value] of formData.entries()) {
        // 检查是否是数组字段 (如 langs[0][name])
        const arrayMatch = key.match(/^([^\[]+)\[(\d+)\]\[([^\]]+)\]$/);
        
        if (arrayMatch) {
            const [, fieldName, index, property] = arrayMatch;
            
            // 初始化数组字段
            if (!arrayFields.has(fieldName)) {
                arrayFields.set(fieldName, []);
            }
            
            // 获取当前数组
            const arr = arrayFields.get(fieldName);
            
            // 确保数组有足够的长度
            while (arr.length <= parseInt(index)) {
                arr.push({});
            }
            
            // 设置属性值
            arr[index][property] = value;
        } else {
            // 普通字段直接设置
            result[key] = value;
        }
    }
    
    // 将处理后的数组添加到结果中
    for (let [fieldName, array] of arrayFields.entries()) {
        // 过滤掉空对象（所有属性都为空的对象）
        result[fieldName] = array.filter(item => 
            Object.values(item).some(val => val !== null && val !== undefined && val !== '')
        );
    }

    return result;
}

// 初始化API文档
function initApiDoc() {
    // 高亮所有代码块
    document.querySelectorAll('pre code').forEach(block => {
        hljs.highlightElement(block);
    });

    // 绑定复制按钮事件
    document.querySelectorAll('.copy-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const target = document.querySelector(this.dataset.target);
            if (target) {
                copyToClipboard(target.textContent);
            }
        });
    });

    // 调试功能
    $('#debugForm').on('submit', async function (e) {
        e.preventDefault();
        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        const $response = $('#responseArea');

        try {
            $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-1"></i>发送中...');

            // 获取表单数据并处理
            const formData = new FormData($form[0]);
            const processedData = processFormData(formData);

            // 获取请求方法和URL
            const method = $form.data('method');
            const apiUrl = $form.data('url');

            // 获取请求头
            const headers = {
                'Content-Type': 'application/json' // 默认使用JSON格式
            };

            // 添加全局请求头
            try {
                const globalHeaders = JSON.parse(localStorage.getItem('api_headers') || '{}');
                Object.assign(headers, globalHeaders);
            } catch (error) {
                console.error('解析全局请求头失败:', error);
            }

            // 添加自定义请求头
            const customHeaders = {};
            $('#customHeaders .header-item').each(function () {
                const key = $(this).find('input:first').val().trim();
                const value = $(this).find('input:last').val().trim();
                if (key && value) {
                    customHeaders[key] = value;
                }
            });
            Object.assign(headers, customHeaders);

            // 发送请求
            const baseUrl = localStorage.getItem('api_base_url') || '';
            let requestUrl = baseUrl + apiUrl;
            let requestConfig = {
                method: method,
                headers: headers
            };

            // 处理请求参数
            if (method === 'GET') {
                // GET请求：将参数拼接到URL
                const params = new URLSearchParams();
                for (let [key, value] of Object.entries(processedData)) {
                    if (Array.isArray(value)) {
                        // 数组参数特殊处理
                        value.forEach((item, index) => {
                            for (let [k, v] of Object.entries(item)) {
                                params.append(`${key}[${index}][${k}]`, v);
                            }
                        });
                    } else {
                        params.append(key, value);
                    }
                }
                const queryString = params.toString();
                if (queryString) {
                    requestUrl += (requestUrl.includes('?') ? '&' : '?') + queryString;
                }
            } else {
                // 非GET请求：将处理后的数据放入body
                requestConfig.body = JSON.stringify(processedData);
            }

            const response = await fetch(requestUrl, requestConfig);

            // 显示响应
            const result = await response.json();
            const formattedJson = JSON.stringify(result, null, 2);
            $response.html(`<pre><code class="hljs language-json">${formattedJson}</code></pre>`);
            hljs.highlightElement($response.find('code')[0]);

        } catch (error) {
            $response.html(`<pre><code class="hljs">Error: ${error.message}</code></pre>`);
        } finally {
            $btn.prop('disabled', false).html('<i class="fa fa-paper-plane me-1"></i>发送请求');
        }
    });

    // 加载全局请求头
    function loadGlobalHeaders() {
        const headers = JSON.parse(localStorage.getItem('api_headers') || '{}');
        const $container = $('#globalHeaders');
        $container.empty();

        Object.entries(headers).forEach(([key, value]) => {
            $container.append(`
                <div class="header-item global">
                    <span class="header-key">${key}:</span>
                    <span class="header-value">${value}</span>
                </div>
            `);
        });
    }

    // 添加自定义请求头
    $('#addHeaderBtn').on('click', function () {
        $('#customHeaders').append(`
            <div class="header-item">
                <input type="text" class="form-control form-control-sm" placeholder="Header Key">
                <input type="text" class="form-control form-control-sm" placeholder="Header Value">
                <button type="button" class="btn-remove">
                    <i class="fa fa-times"></i>
                </button>
            </div>
        `);
    });

    // 移除自定义请求头
    $(document).on('click', '.btn-remove', function () {
        $(this).closest('.header-item').remove();
    });

    // 初始加载全局请求头
    loadGlobalHeaders();
} 